package com.tianheng.wanzhou.datacollecting.netty.kongyajiSamsung.client;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianheng.wanzhou.datacollecting.DataCollectingApplication;
import com.tianheng.wanzhou.datacollecting.db.entity.AirCompressorAmpsHis;
import com.tianheng.wanzhou.datacollecting.db.entity.AirCompressorPowerHis;
import com.tianheng.wanzhou.datacollecting.db.entity.AirCompressorSamsung;
import com.tianheng.wanzhou.datacollecting.db.entity.MachineList;
import com.tianheng.wanzhou.datacollecting.db.service.IAirCompressorAmpsHisService;
import com.tianheng.wanzhou.datacollecting.db.service.IAirCompressorPowerHisService;
import com.tianheng.wanzhou.datacollecting.db.service.IAirCompressorSamsungService;
import com.tianheng.wanzhou.datacollecting.db.service.IMachineListService;
import com.tianheng.wanzhou.datacollecting.util.FloatOperate;
import com.tianheng.wanzhou.datacollecting.util.SerializeUtil;
import com.tianheng.wanzhou.datacollecting.util.StrUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.ReferenceCountUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: yujw
 * @Date: 2020/5/12 14:26
 * @Version 1.0
 */
@Slf4j
@Component(value = "kongyajiSamsungHandler")
@Scope("prototype")
public class ClientHandler extends ChannelInboundHandlerAdapter {

    @Autowired
    IAirCompressorSamsungService samsungService;


//    @Autowired
//    IAirCompressorAmpsHisService ampsHisService;
//
//    @Autowired
//    IAirCompressorPowerHisService powerHisService;

    @Autowired
    IMachineListService machineListService;
    private List<MachineList> machineList = new ArrayList<>();

//    @Resource
//    Jedis jedis;

    private static ClientHandler clientHandler;

    @PostConstruct
    public void init() {
        clientHandler = this;
        samsungService = this.samsungService;
        QueryWrapper<MachineList> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mac_type", 2).eq("status", 1).eq("son_type", "03");
        machineList = machineListService.list(queryWrapper);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress inSocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = inSocket.getAddress().getHostAddress();
        log.info("连接服务端" + clientIP + "成功!");
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
//        MachineList machine = (MachineList) SerializeUtil.deserialize(jedis.get(clientIP.getBytes()));
        try {
            MachineList machine = new MachineList();
            for (MachineList machine1 : this.machineList) {
                if(clientIP.equals(machine1.getMacIp())){
                    machine =machine1;
                    break;
                }
            }
            ByteBuf buf = (ByteBuf)msg;
            byte[] bytes = new byte[buf.readableBytes()];
            buf.readBytes(bytes);
            String str = StrUtil.bytesToHexString(bytes);
            log.info("收到数据:" + str);
            String length = str.substring(4, 6).toLowerCase();
            String data = str.substring(6, str.length() - 4);
            AirCompressorSamsung airCompressor = new AirCompressorSamsung();
            airCompressor.setCompany(machine.getCompany());
            airCompressor.setWorkshop(machine.getWorkshop());
            airCompressor.setMachineIp(machine.getMacIp());
            airCompressor.setMachineId(machine.getMacId());
//            if (length.equals("0e")) {
//                char[] s1 = StrUtil.hexStr2BinaryStr(data.substring(0, 2)).toCharArray();
//                char[] s2 = StrUtil.hexStr2BinaryStr(data.substring(2, 4)).toCharArray();
//                char[] s3 = StrUtil.hexStr2BinaryStr(data.substring(4, 6)).toCharArray();
//                char[] s4 = StrUtil.hexStr2BinaryStr(data.substring(6, 8)).toCharArray();
//                char[] s5 = StrUtil.hexStr2BinaryStr(data.substring(8, 10)).toCharArray();
//                char[] s6 = StrUtil.hexStr2BinaryStr(data.substring(10, 12)).toCharArray();
//                char[] s7 = StrUtil.hexStr2BinaryStr(data.substring(12, 14)).toCharArray();
//                airCompressor.setCompressorReady(Character.digit(s1[0], 2));
//                airCompressor.setTotalWarning(Character.digit(s1[1], 2));
//                airCompressor.setTotalTripFault(Character.digit(s1[2], 2));
//                airCompressor.setCompressorRunStop(Character.digit(s1[3], 2));
//                airCompressor.setOilHeaterOn(Character.digit(s1[4], 2));
//                airCompressor.setAuxiliaryOilPumpOn(Character.digit(s1[5], 2));
//                airCompressor.setUnloadAutoloadSW(Character.digit(s1[6], 2));
//                airCompressor.setUnloadLoad(Character.digit(s1[10], 2));
//                airCompressor.setLocalRemote(Character.digit(s1[11], 2));
//
//                airCompressor.setCommonShutdownOn(Character.digit(s2[0], 2));
//                airCompressor.setDriveMotorNotFullyStopper(Character.digit(s2[1], 2));
//                airCompressor.setOilSupplyPressureLow(Character.digit(s2[2], 2));
//                airCompressor.setOilSupplyTemperatureLow(Character.digit(s2[3], 2));
//                airCompressor.setEmergencyStopButtonPressed(Character.digit(s2[4], 2));
//                airCompressor.setControllerError(Character.digit(s2[5], 2));
//                airCompressor.setIgvNotPrePosition(Character.digit(s2[7], 2));
//                airCompressor.setBovNotPrePosition(Character.digit(s2[8], 2));
//                airCompressor.setDischargeCheckValveFailure(Character.digit(s2[9], 2));
//                airCompressor.setControllerSignalFailure(Character.digit(s2[10], 2));
//                airCompressor.setRemoteStopButtonPressed(Character.digit(s2[12], 2));
//                airCompressor.setNormalStopButtonPressed(Character.digit(s2[14], 2));
//
//                airCompressor.setSurgeAlarm(Character.digit(s3[0], 2));
//                airCompressor.setControllerError1(Character.digit(s3[1], 2));
//                airCompressor.setOilLevelAlarm(Character.digit(s3[2], 2));
//                airCompressor.setAuxOilPumpTrip(Character.digit(s3[6], 2));
//                airCompressor.setOilSupplyPressureLowAlarm(Character.digit(s3[8], 2));
//                airCompressor.setVibrationStage1HighAlarm(Character.digit(s3[9], 2));
//                airCompressor.setVibrationStage2HighAlarm(Character.digit(s3[10], 2));
//                airCompressor.setMotorCurrentAlarm(Character.digit(s3[13], 2));
//                airCompressor.setOilSupplyTemperatureHighAlarm(Character.digit(s3[14], 2));
//                airCompressor.setStage2InletTemperatureHighAlarm(Character.digit(s3[15], 2));
//
//                airCompressor.setOilReservoirTemperatureLowAlarm(Character.digit(s4[0], 2));
//                airCompressor.setMotorCoilRTemperatureHighAlarm(Character.digit(s4[1], 2));
//                airCompressor.setDischargeCheckVvAlarm(Character.digit(s4[11], 2));
//                airCompressor.setPreSurgeAlarm(Character.digit(s4[12], 2));
//                airCompressor.setOilHeaterTrip(Character.digit(s4[13], 2));
//                airCompressor.setRtdSignalFault(Character.digit(s4[14], 2));
//                airCompressor.setAnalogSignalFault(Character.digit(s4[15], 2));
//
//                airCompressor.setSurgeShutdown(Character.digit(s6[0], 2));
//                airCompressor.setOilLevelShutdown(Character.digit(s6[2], 2));
//                airCompressor.setOilSupplyPressureLowDanger(Character.digit(s6[8], 2));
//                airCompressor.setVibrationStage1HighDanger(Character.digit(s6[9], 2));
//                airCompressor.setVibrationStage2HighDanger(Character.digit(s6[10], 2));
//                airCompressor.setOilSupplyTemperatureHighDanger(Character.digit(s6[14], 2));
//                airCompressor.setStage2InletTemperatureHighDanger(Character.digit(s6[15], 2));

//                airCompressor.setShutPowerOff(Character.digit(s7[1], 2));
//                airCompressor.setShutPowerOff(Character.digit(s7[6], 2));
//                airCompressor.setShutPowerOff(Character.digit(s7[7], 2));
//                airCompressor.setShutPowerOff(Character.digit(s7[10], 2));
//                airCompressor.setShutPowerOff(Character.digit(s7[11], 2));
//                airCompressor.setShutPowerOff(Character.digit(s7[12], 2));
//                airCompressor.setShutPowerOff(Character.digit(s7[13], 2));
//                airCompressor.setShutPowerOff(Character.digit(s7[14], 2));
//                airCompressor.setShutPowerOff(Character.digit(s7[15], 2));
//            }
            if (length.equals("58")) {
                airCompressor.setCommunicationHearbeat(FloatOperate.decimal(data.substring(0, 8)));
                airCompressor.setIgvPositionOpen(FloatOperate.decimal(data.substring(8, 16)));
                airCompressor.setBovPositionClosed(FloatOperate.decimal(data.substring(16, 24)));
                airCompressor.setSystemPressure(FloatOperate.decimal(data.substring(24, 32)));
                airCompressor.setStage2DischargePressure(FloatOperate.decimal(data.substring(32, 40)));
                airCompressor.setOilSupplyPressure(FloatOperate.decimal(data.substring(40, 48)));
                airCompressor.setStage1Vibration(FloatOperate.decimal(data.substring(48, 56)));
                airCompressor.setStage2Vibration(FloatOperate.decimal(data.substring(56, 64)));
                airCompressor.setMotorCurrent(FloatOperate.decimal(data.substring(80, 88)));
                airCompressor.setOilSupplyTemperature(FloatOperate.decimal(data.substring(88, 96)));
                airCompressor.setStage2InletTemperature(FloatOperate.decimal(data.substring(96, 104)));
                airCompressor.setOilReservoirTemperature(FloatOperate.decimal(data.substring(104, 112)));
                airCompressor.setMotorWindingRTeperature(FloatOperate.decimal(data.substring(112, 120)));
                airCompressor.setMotorBearingDeTemperature(FloatOperate.decimal(data.substring(120, 128)));
                airCompressor.setMotorBearingNdeTemperature(FloatOperate.decimal(data.substring(128, 136)));
                airCompressor.setCompressorRuntime(FloatOperate.decimal(data.substring(136, 144)));
                airCompressor.setCompressorLoadTime(FloatOperate.decimal(data.substring(144, 152)));
                airCompressor.setSetPoint(FloatOperate.decimal(data.substring(152, 160)));
                airCompressor.setUnloadSetPoint(FloatOperate.decimal(data.substring(160, 168)));
                airCompressor.setReloadSetPoint(FloatOperate.decimal(data.substring(168, 176)));

//                AirCompressorPowerHis powerHis = new AirCompressorPowerHis();
//                AirCompressorAmpsHis ampsHis = new AirCompressorAmpsHis();
//                ampsHis.setMachineId(airCompressor.getMachineId());
//                ampsHis.setMachineIp(airCompressor.getMachineIp());
//                ampsHis.setWorkshop(airCompressor.getWorkshop());
//                ampsHis.setMotorAmps(airCompressor.getMotorCurrent().toString());
//                ampsHisService.save(ampsHis);
//                powerHis.setMachineIp(airCompressor.getMachineIp());
//                powerHis.setMachineId(airCompressor.getMachineId());
//                powerHis.setPowerConsumption(airCompressor.getMotorCurrent() * 1.2452);
//                powerHis.setWorkshop(airCompressor.getWorkshop());
//                powerHisService.save(powerHis);
            }
            if (length.equals("08")) {
                airCompressor.setMotorMinAmpere(FloatOperate.decimal(data.substring(0, 4)));
                airCompressor.setMotorMaxAmpere(FloatOperate.decimal(data.substring(4, 8)));

            }
//            DataCollectingApplication.ampsHis.put(clientIP, airCompressor.getMotorCurrent());
//            DataCollectingApplication.powerHis.put(clientIP, (airCompressor.getMotorCurrent() * 1.2452 ));
            samsungService.saveOrUpdate(airCompressor);
            if (length.equals("08")) {
                ctx.channel().close();
                ctx.close();
            }

        }finally {
            ReferenceCountUtil.release(msg);
        }

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("数据读取完毕");
    }

    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIP = insocket.getAddress().getHostAddress();
        log.info("连接"+ clientIP +"移除");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("发生错误:" + cause.toString());
        ctx.close();
    }

}
